package com.bauer.java.metadata;

import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;

/**
 * @Author ：rui.wei
 * @Date ：Created in 11:24 2019/9/17
 * @Description：
 */
public class OracleMetaData {

    public static void main(String[] args) throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-mybatis.xml");

        DataSource dataSource = (DataSource) context.getBean("dataSourceOracle");
        Connection connection = dataSource.getConnection();
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        ResultSet resultSet = databaseMetaData.getSchemas();
        while (resultSet.next()) {
            System.out.println(resultSet.getString(1));
            if (!"DIP".equals(resultSet.getString(1))) {
                continue;
            }
            ResultSet functionsRes = databaseMetaData.getFunctions(null, resultSet.getString(1), "%");



            //获取
            ResultSet tableResult = databaseMetaData.getTables(null, resultSet.getString(1), "%", new String[]{"TABLE"});
            while (tableResult.next()) {
                System.out.print("    ");
                System.out.println(tableResult.getString("TABLE_NAME"));
                ResultSet colResult = databaseMetaData.getColumns(resultSet.getString(1), null, tableResult.getString("TABLE_NAME"), "%");
                while (colResult.next()) {
                    System.out.print("        ");
                    System.out.print(colResult.getString("COLUMN_NAME"));
                    System.out.print("|");
                    //数据类型
                    System.out.print(colResult.getString("TYPE_NAME"));
                    System.out.print("|");

                    //长度
                    System.out.print(colResult.getString("COLUMN_SIZE"));
                    System.out.print("|");

                    //精度
                    System.out.print(colResult.getString("DECIMAL_DIGITS"));
                    System.out.print("|");

                    //默认值
                    System.out.print(colResult.getString("COLUMN_DEF"));
                    System.out.print("|");

                    //是否可空
                    System.out.print(colResult.getString("NULLABLE"));
                    System.out.print("|");
                    //备注
                    System.out.print(colResult.getString("REMARKS"));
                    System.out.print("|");
                    System.out.println();
                }
            }

        }
        connection.close();
    }
}
